﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.ScheduleJob.SPI;

namespace T.FAS.Runtime.ScheduleJob.Service
{
    public class DelayTriggerBuilder : ITriggerBuilder
    {
        public ITrigger Build(ScheduleJobExecContext context)
        {
            var builder = TriggerBuilder.Create()
                .WithIdentity(context.TriggerKey)
                .WithSimpleSchedule(m =>
                {
                    m.WithRepeatCount(0);
                    var misfirePolicy = context.ScheduleJobMetaData.ScheduleTrigger.MisfirePolicy;
                    if (misfirePolicy == Metadata.Entity.ScheduleJob.MisfirePolicy.Schedule_DoAllMisfires)
                        m.WithMisfireHandlingInstructionIgnoreMisfires();
                    else if (misfirePolicy == Metadata.Entity.ScheduleJob.MisfirePolicy.Schedule_IgnoreMisfire)
                        m.WithMisfireHandlingInstructionNextWithRemainingCount();
                    else
                        m.WithMisfireHandlingInstructionFireNow();
                }
                );

            //指定了生效时间
            if (context.ScheduleJobMetaData.ScheduleTrigger.EffectiveTime != null)
            {
                builder = builder.StartAt(context.ScheduleJobMetaData.ScheduleTrigger.EffectiveTime.AddSeconds(context.ScheduleJobMetaData.ScheduleTrigger.DelayTime));
            }
            TriggerCommonUtil.ConstructBuilder(builder, context.ScheduleJobMetaData);


            var trigger = builder.Build();
            
            return trigger;
        }
    }
}
